package com.shelpe.services.simbasync.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shelpe.services.simbasync.dao.CategoryMapper;
import com.shelpe.services.simbasync.model.Category;
import com.shelpe.services.simbasync.model.CategoryExample;
import com.shelpe.services.simbasync.model.mongo.InsightCatData;
import com.shelpe.services.simbasync.mongorepository.InsightCatDataRepository;
import com.shelpe.services.simbasync.service.CategoryService;
import com.shelpe.services.simbasync.service.simbaproxy.CategoryProxy;
import com.shelpe.services.simbasync.service.simbaproxy.CategoryProxy.CategoryDto;
import com.shelpe.services.simbasync.service.simbaproxy.CategoryProxy.CategoryListRespone;
import com.shelpe.services.simbasync.service.simbaproxy.CategoryProxy.InsightCatDataDto;
import com.shelpe.services.simbasync.service.simbaproxy.CategoryProxy.InsightCatDataResponse;

@Service
public class CategoryServiceImpl implements CategoryService{

	private static final Logger logger = LoggerFactory.getLogger(CategoryServiceImpl.class);
	
	@Autowired
	private CategoryMapper catMaper;
	
	@Autowired
	private CategoryProxy catProxy;
	
	@Autowired
	private InsightCatDataRepository insightCatRep;
	
	@Override
	public List<Category> getCategoryListByIds(List<Integer> cids){
		
		CategoryExample ex = new CategoryExample();
		ex.createCriteria().andCatIdIn(cids);
		
		return catMaper.selectByExample(ex);
	}
	
	@Override
	public int insertCategoryList(List<Category> catList){
		
		int num = 0;
		if(catList != null && catList.size() > 0){
			
			num = catMaper.insertBatch(catList);
		}
		
		return num;
	}
	
	@Override
	public List<Category> getCategoryFromProxy(Long userId, List<Integer> cids){
		
		List<Category> result = new ArrayList<Category>();
		
		if(cids == null || cids.size() == 0){
			return result;
		}
		Set<Integer> catIdSet = new HashSet<Integer>();
		int pageSize = 20;
		int fromIndex = 0;
		int endIndex = 0;
		
		do{
			endIndex += pageSize; 
			if(endIndex > cids.size()){
				endIndex = cids.size();
			}
			
			StringBuilder sb = new StringBuilder();
			int index = fromIndex;
			for(; index < endIndex-1; index++){
				sb.append(cids.get(index));
				sb.append(",");
			}
			sb.append(cids.get(index));
			int type = 1;
			CategoryListRespone res = null;
			
			try{
				res = catProxy.getCategory(userId, type, sb.toString());
			}catch(Exception e){
				logger.warn("getCategoryFromProxy something is wrong, {}", e);
			}
			
			if(res != null && res.getRes() != null && res.getRes().getDataList() != null){
				
				List<CategoryDto> categoryDto = res.getRes().getDataList().getCategories();
				if(categoryDto != null && categoryDto.size() > 0){
					
					for(CategoryDto dto : categoryDto){
						if(!catIdSet.contains(dto.getCategoryID())){
							catIdSet.add(dto.getCategoryID());
							Category item = new Category();
							item.setCatId(dto.getCategoryID());
							item.setCatName(dto.getName());
							item.setCatLevel(dto.getLevel());
							item.setCatPathId(dto.getCategoryIDs());
							item.setParentCatId(dto.getParentID());
							item.setCatPathName(dto.getNames());
							
							result.add(item);
						}else{
							logger.warn(">>>getCategoryFromProxy dup cat_id {}", dto.getCategoryID());
						}
					}
				}
			}
			
			fromIndex += pageSize; 
		}while(fromIndex < cids.size());
		
		return result;
	}

	@Override
	public void saveInsightCategoryData(List<InsightCatData> list) {
		// TODO Auto-generated method stub
		insightCatRep.save(list);
	}

	@Override
	public List<InsightCatData> getInsightCategoryData(Long userId, String catIds, String startDate, String endDate) {
		// TODO Auto-generated method stub
		
		List<InsightCatData> result = new ArrayList<InsightCatData>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date startDateFormat = new Date();
		Date endDateFormat = new Date();
		
		try {
			startDateFormat = sdf.parse(startDate);
			endDateFormat = sdf.parse(endDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		int pageSize = 5;
		int fromIndex = 0;
		int endIndex = 0;
		String[] catIdArray = catIds.split(",");
		
		do{
			endIndex += pageSize; 
			if(endIndex > catIdArray.length){
				endIndex = catIdArray.length;
			}
			
			StringBuilder sb = new StringBuilder();
			int index = fromIndex;
			for(; index < endIndex-1; index++){
				sb.append(catIdArray[index]);
				sb.append(",");
			}
			sb.append(catIdArray[index]);
			InsightCatDataResponse res = catProxy.getInsightData(userId, sb.toString(), startDate, endDate);
			
			if(res != null && res.getRes() != null && res.getRes().getDataList() != null){
				
				List<InsightCatDataDto> dto = res.getRes().getDataList().getDto();
				
				if(dto != null && dto.size() > 0){
					for(InsightCatDataDto item : dto){
						
						InsightCatData data = new InsightCatData();	 
						BeanUtils.copyProperties(item, data);
						data.setStartDate(startDateFormat);
						data.setEndDate(endDateFormat);
						result.add(data);
					}
				}
			}
			
			fromIndex += pageSize; 
			
		}while(fromIndex < catIdArray.length);
		
		return result;
	}
	
}
